//
//  MXDropdownMenu.m
//  MXの衣柜
//
//  Created by 马霄 on 15/8/19.
//  Copyright (c) 2015年 霄 马. All rights reserved.
//

#import "MXDropdownMenu.h"
#import "UIView+Extension.h"


@interface MXDropdownMenu ()
@property (nonatomic, retain) UIImageView *containerView;

@end
@implementation MXDropdownMenu
- (void)dealloc
{
    [_contentController release];
    [_content release];
    [super dealloc];
}

- (UIImageView *)containerView
{
    if (!_containerView) {
        // 添加一个灰色图片控件
        UIImageView *containerView = [[[UIImageView alloc] init] autorelease];
        containerView.image = [UIImage imageNamed:@"dropMenu"];
        containerView.userInteractionEnabled = YES;
        [self addSubview:containerView];
        self.containerView = containerView;
    }
    return _containerView;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 清除颜色
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

+ (instancetype)menu
{
    return [[self alloc] init];
}

-(void)setContent:(UIView *)content
{
    if (_content != content) {
        [_content release];
        _content = [content retain];
    }
    // 调整内容位置
    content.x = WIDTHPRO * 5;
    content.y = HEIGHTPRO * 15;
    
    // 调整内容的宽度
    
    // 设置灰色的高度
    self.containerView.height = CGRectGetMaxY(content.frame) + HEIGHTPRO * 10;
    self.containerView.width = CGRectGetMaxX(content.frame) + WIDTHPRO * 10;
    // 添加内容到灰色图片中
    [self.containerView addSubview:content];
}

-(void)setContentController:(UIViewController *)contentController
{
    if (_contentController != contentController) {
        [_contentController release];
        _contentController = [contentController retain];
    }
        
    self.content = contentController.view;
}


/**
 * 显示
 */
- (void)showFrom:(UIView *)from
{
    // 1.获得最上面的窗口
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    
    // 2.添加到自己的窗口上
    [window addSubview:self];
    
    // 3.设置尺寸
    self.frame = window.bounds;
    
    // 4.调整灰色图片的位置
    // 默认情况下, frame是以父控件左上角为坐标原点
    CGRect newFrame = [from convertRect:from.bounds toView:window];
    
    self.containerView.centerX = CGRectGetMidX(newFrame);
    self.containerView.y = CGRectGetMaxY(newFrame);
    
    // 通知外界, 自己显示了
    if ([self.delegate respondsToSelector:@selector(dropdownMenuDidShow:)]) {
        [self.delegate dropdownMenuDidShow:self];
    }
}

/**
 * 销毁
 */
- (void)dismiss
{
    [self removeFromSuperview];
    // 通知外界 , 自己销毁了
    if ([self.delegate respondsToSelector:@selector(dropdownMenuDidDismiss:)]) {
        [self.delegate dropdownMenuDidDismiss:self];
    }
    
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self dismiss];
}

@end
